package com.ruoyi.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 虚拟线程日志工具类
 * 提供虚拟线程的监控和日志记录功能
 * 
 * @author ruoyi
 */
public class VirtualThreadLogger {
    
    private static final Logger virtualThreadLogger = LoggerFactory.getLogger("virtual-thread");
    private static final Logger performanceLogger = LoggerFactory.getLogger("virtual-thread-performance");
    
    private static final AtomicLong requestCounter = new AtomicLong(0);
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    
    /**
     * 记录虚拟线程基本信息
     */
    public static void logThreadInfo(String operation) {
        Thread currentThread = Thread.currentThread();
        long requestId = requestCounter.incrementAndGet();
        
        // 设置MDC上下文
        MDC.put("requestId", String.valueOf(requestId));
        MDC.put("threadType", currentThread.isVirtual() ? "Virtual" : "Platform");
        MDC.put("threadName", currentThread.getName());
        
        virtualThreadLogger.info("Operation: {} | Thread: {} | IsVirtual: {} | ThreadId: {}", 
            operation, 
            currentThread.getName(), 
            currentThread.isVirtual(),
            currentThread.threadId());
    }
    
    /**
     * 记录虚拟线程性能信息
     */
    public static void logPerformance(String operation, long startTime, long endTime) {
        Thread currentThread = Thread.currentThread();
        long duration = endTime - startTime;
        
        performanceLogger.info("Performance | Operation: {} | Thread: {} | IsVirtual: {} | Duration: {}ms | Start: {} | End: {}", 
            operation,
            currentThread.getName(),
            currentThread.isVirtual(),
            duration,
            LocalDateTime.now().minusNanos((endTime - startTime) * 1_000_000).format(formatter),
            LocalDateTime.now().format(formatter));
    }
    
    /**
     * 记录虚拟线程异常信息
     */
    public static void logError(String operation, Exception e) {
        Thread currentThread = Thread.currentThread();
        
        virtualThreadLogger.error("Error in Operation: {} | Thread: {} | IsVirtual: {} | Error: {}", 
            operation,
            currentThread.getName(),
            currentThread.isVirtual(),
            e.getMessage(), e);
    }
    
    /**
     * 记录虚拟线程启动信息
     */
    public static void logThreadStart(String taskName) {
        Thread currentThread = Thread.currentThread();
        
        virtualThreadLogger.debug("Thread Started | Task: {} | Thread: {} | IsVirtual: {} | ThreadId: {} | State: {}", 
            taskName,
            currentThread.getName(),
            currentThread.isVirtual(),
            currentThread.threadId(),
            currentThread.getState());
    }
    
    /**
     * 记录虚拟线程结束信息
     */
    public static void logThreadEnd(String taskName) {
        Thread currentThread = Thread.currentThread();
        
        virtualThreadLogger.debug("Thread Ended | Task: {} | Thread: {} | IsVirtual: {} | ThreadId: {}", 
            taskName,
            currentThread.getName(),
            currentThread.isVirtual(),
            currentThread.threadId());
            
        // 清理MDC
        MDC.clear();
    }
    
    /**
     * 记录虚拟线程池状态
     */
    public static void logThreadPoolStatus() {
        // 获取当前JVM线程信息
        ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
        ThreadGroup parentGroup;
        while ((parentGroup = rootGroup.getParent()) != null) {
            rootGroup = parentGroup;
        }
        
        performanceLogger.info("ThreadPool Status | Active Threads: {} | Available Processors: {} | Free Memory: {}MB | Total Memory: {}MB", 
            rootGroup.activeCount(),
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().freeMemory() / (1024 * 1024),
            Runtime.getRuntime().totalMemory() / (1024 * 1024));
    }
    
    /**
     * 创建带有日志记录的虚拟线程
     */
    public static Thread createVirtualThread(String taskName, Runnable task) {
        return Thread.ofVirtual()
            .name("vt-" + taskName + "-" + requestCounter.incrementAndGet())
            .start(() -> {
                logThreadStart(taskName);
                long startTime = System.currentTimeMillis();
                try {
                    task.run();
                } catch (Exception e) {
                    logError(taskName, e);
                    throw e;
                } finally {
                    long endTime = System.currentTimeMillis();
                    logPerformance(taskName, startTime, endTime);
                    logThreadEnd(taskName);
                }
            });
    }
    
    /**
     * 获取当前请求ID
     */
    public static String getCurrentRequestId() {
        return MDC.get("requestId");
    }
    
    /**
     * 检查当前线程是否为虚拟线程
     */
    public static boolean isCurrentThreadVirtual() {
        return Thread.currentThread().isVirtual();
    }
} 